package com.sky.module.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.sky.config.redis.RedisService;
import com.sky.module.system.loginlog.domain.dto.LoginLogDto;
import com.sky.module.system.loginlog.service.LoginLogService;
import com.sky.module.system.user.domain.entity.User;
import com.sky.module.system.utils.JwtUtils;
import com.sky.utils.LoginResult;
import com.sky.utils.ResultCode;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/***
 * @description 登录成功处理器
 * @param null
 * @return
 * @date 2023/2/20 9:56
 *
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtUtils jwtUtils;

    @Autowired
    private LoginLogService loginLogService;
    @Resource
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
        chain.doFilter(request, response);

    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//            设置响应编码格式
        response.setContentType("application/json;charset=utf-8");
//         获取当前登录用户
        User user = (User) authentication.getPrincipal();
        user.setPassword("");

        String token = jwtUtils.generateToken(user);
        long expireTime = Jwts.parser() //获取DefaultJwtParser对象
                .setSigningKey(jwtUtils.getSecret()) //设置签名的密钥
                .parseClaimsJws(token.replace("jwt_", ""))
                .getBody().getExpiration().getTime();//获取token过期时间


//         创建loginResult 结果对象
        final LoginResult loginResult = new LoginResult(user.getId(), ResultCode.SUCCESS);
        loginResult.setExpireTime(expireTime);
        loginResult.setToken(token);

        //            将对象转换成JSON格式化 取出循环引用
        final String jsonString = JSON.toJSONString(loginResult, SerializerFeature.DisableCircularReferenceDetect);
        final ServletOutputStream outputStream = response.getOutputStream();
//         写数据
        outputStream.write(jsonString.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
//        将用户信息 token 保存到redis 中
        String tokenKey = "token_" + token;

        // 保存登录日志信息
        loginLogService.saveLoginLogInfoSuccess();
        redisService.set(tokenKey, token, jwtUtils.getExpiration() / 1000);

//        TODO 成功登陆一次就 +1 还有每周的登录次数

    }


}
